// pages/consultation/quiz/quiz.js
const app = getApp()
var help = require('../../../utils/help.js');
var login = require('../../../utils/login.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    //图片上传
    files: [
      {
        url: '',
      }, 
      {
        loading: false
      }, 
      {
        error: false
      }
    ],

    imageUrl: app.data.imageUrl,

    id: 0,
    data: {},
    msg: '',
    product_images: [],
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    //图片上传
    this.setData({
      selectFile: this.selectFile.bind(this),
      uplaodFile: this.uplaodFile.bind(this)
    })
    if (options.id) {
      this.setData({
        id: options.id
      })
    }
  },
  //上传图片
  chooseImage: function (e) {
    var that = this;
    wx.chooseImage({
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function (res) {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        that.setData({
          files: that.data.files.concat(res.tempFilePaths)
        });
      }
    })
  },
  previewImage: function (e) {
    wx.previewImage({
      current: e.currentTarget.id, // 当前显示图片的http链接
      urls: this.data.files // 需要预览的图片http链接列表
    })
  },
  selectFile(files) {
    console.log('files', files)
    // 返回false可以阻止某次文件上传
  },
  uplaodFile(files) {
    console.log('upload files', files)
    // 文件上传的函数，返回一个promise
    // return new Promise((resolve, reject) => {
    //   setTimeout(() => {
    //     reject('some error')
    //   }, 1000)
    // })
    var that = this;

      return new Promise(function (resolve, reject) {
        var imgPath = files.tempFilePaths[0]
        if (imgPath != "") {

          wx.uploadFile({

            url: app.data.apiUrl + 'Common/upload',//开发者服务器url

            filePath: imgPath,

            name: 'file',

            header: {

              "Content-Type": "multipart/form-data"

            },

            formData: {
              token: app.data.userInfo ? app.data.userInfo.token : '',
            },

            success: function (res) {

              var data = JSON.parse(res.data)
              console.log(data)
              that.data.product_images.push(data.data.url_all)
              // that.data.product_images = data.data.url_all
              console.log(that.data.product_images)
              that.setData({
                product_images: that.data.product_images
              })
              that.data.product_images
              resolve(that.data.product_images);//这里要加resolve（）函数，参数可为空，不加的话promise无法达到预期效果。

              console.log("success");

            },

            fail: function (err) {

              reject();//同样要加reject

              console.log("fail");

            },

          });

        } else {

          resolve();

        }

      });



  },
  uploadError(e) {
    console.log('upload error', e.detail)
  },
  uploadSuccess(e) {
    console.log('upload success', e.detail)
  },
  set_msg: function (e) {
    this.setData({
      msg: e.detail.value
    })
  },

  sub: function (e) {
    var that = this;
    var url = app.data.apiUrl + 'Zxorder/tiwen';
    var data = {
      token: app.data.userInfo ? app.data.userInfo.token : '',
      id: that.data.id,
      msg: that.data.msg,
      images: that.data.product_images.join(',')
    };
    help.get(url, data, that, function (res, that) {
      var result = res.data;
      // console.log(result);
      if (result.code == 1) {
        help.msg('提交成功');
        setTimeout(function(){
          wx.redirectTo({
            url: '/pages/consultation/consult/consult?yisheng_id=' + that.data.data.yisheng_id
          })
        }, 500)
      } else {
        help.msg(result.msg)
        return false;
      }

    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.loadBaseData();
  },
  loadBaseData: function () {
    var that = this;
    //医生
    help.get(app.data.apiUrl + 'Zxorder/orderInfo', {
      token: app.data.userInfo ? app.data.userInfo.token : '',
      id: that.data.id
    }, that, function (res, that) {
      var result = res.data;
      // console.log(result);
      if (result.code == 1) {
        that.setData({
          data: result.data,
        })
        if (result.data.msg_list) {
          that.setData({
            msg: result.data.msg_list[0].msg,
            product_images: result.data.msg_list[0].images
          })
        }
      }

    });
  },


  // 上传图片
  chooseImg: function () {
    var that = this;
    var max_count = 5 - that.data.product_images.length;
    if (max_count <= 0) {
      help.msg('最多上传5张图片');
      return false;
    }
    wx.chooseImage({
      count: max_count,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: function (res) {
        var tempFilePaths = res.tempFilePaths
        wx.showLoading({
          title: '正在上传...',
        })
        console.log(tempFilePaths)
        for (var i = 0; i < tempFilePaths.length; i++) {
          wx.uploadFile({
            url: app.data.apiUrl + 'Common/upload',
            filePath: tempFilePaths[i],
            name: 'file',
            formData: {
              token: app.data.userInfo ? app.data.userInfo.token : '',
            },
            success: function (res) {
              var data = JSON.parse(res.data)
              console.log(data)
              that.data.product_images.push(data.data.url_all)
              // that.data.product_images = data.data.url_all
              console.log(that.data.product_images)
              that.setData({
                product_images: that.data.product_images
              })
            }
          })
        }
        setTimeout(function () {
          wx.hideLoading()
        }, 2000)
      },
      fail: function () {
        that.tips('选取图片失败')
      }
    })
  },

  /**
   * 删除图片
   */
  delimg: function (e) {
    var that = this;
    var new_img = [];
    var i = 0;
    for (i in that.data.product_images) {
      if (that.data.product_images[i] != e.currentTarget.dataset.src) {
        new_img.push(that.data.product_images[i])
      }
    }
    that.setData({
      product_images: new_img
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})